package ynu.edu.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import ynu.edu.Util.PropertiesUtil;

import java.io.IOException;
import java.util.Properties;

@Service
public class YsToken {
    @Value("${ys.token_url}")
    private String ysApiUrl;

    @Value("${ys.account_Id}")
    private String accountId;

    @Resource
    private PropertiesUtil propertiesUtil;

    private String accessToken;
    private long tokenExpiryTime;

    public String getAccessToken() {
        Properties properties = propertiesUtil.loadProperties();
        String storedAccessToken = properties.getProperty("ys_access_token");
        String storedExpiryTime = properties.getProperty("ys_expires_Time");

        if (storedAccessToken != null && storedExpiryTime != null) {
            long expiryTime = Long.parseLong(storedExpiryTime);
            if (System.currentTimeMillis() < expiryTime) {
                accessToken = storedAccessToken;
                tokenExpiryTime = expiryTime;
                return accessToken;
            }
        }

        fetchAccessToken();
        return accessToken;
    }
    public void fetchAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        String requestBody = String.format("{\"accountId\": \"%s\"}", accountId);

        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(ysApiUrl, requestEntity, String.class);
        System.out.println("请求萤石token");
        if (response.getStatusCode().is2xxSuccessful()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonResponse = objectMapper.readTree(response.getBody());
                JsonNode dataNode = jsonResponse.get("data");
                accessToken = dataNode.get("accessToken").asText();
                tokenExpiryTime = dataNode.get("expireTime").asLong();

                Properties properties = propertiesUtil.loadProperties();
                properties.setProperty("ys_access_token", accessToken);
                properties.setProperty("ys_expires_Time", String.valueOf(tokenExpiryTime));

                propertiesUtil.saveProperties(properties);

            } catch (IOException e) {
                System.out.println("Failed to parse JSON response: " + e.getMessage());
            }
        } else {
            System.out.println("Failed to fetch access token, status code: " + response.getStatusCode());
        }
    }
}
